import {
    Button,
    Input,
    Modal,
    ModalBody,
    ModalContent,
    ModalFooter,
    ModalHeader,
    Textarea,
    useDisclosure,
    Image
} from "@nextui-org/react";
import React, { useRef, useState } from "react";
import { BiFolderOpen, BiLabel, BiUpload, BiX } from "react-icons/bi";
import createAxiosClient from "@/app/utils/axiosRequest";
import ToastUtil from "@/app/utils/toastUtil";
import EmojiSelect from "@/app/components/tools/EmojiSelect";
import PubSub from "pubsub-js";

/**
 * 创建新的文件夹
 * @param isOpenFolder
 * @param onOpenChangeFolder
 * @param parentId
 * @constructor
 */
export default function CreateFolder({ isOpenFolder, onOpenChangeFolder, parentId }: any) {
    //axios接口
    const axiosInstance = createAxiosClient();
    /*获取的数据 -- Emoji*/
    const [emoji, setEmoji] = useState('📂');
    /*选择表情*/
    const { isOpen: isSelectEmoji, onOpen: onOpenSelectEmoji, onOpenChange: onSelectChange } = useDisclosure();
    /*定义目录名和简介状态*/
    const [folderData, setFolderData] = useState({
        name: '',
        description: '',
        icon: '', // icon URL字段
    });

    // 文件上传相关状态
    const [uploading, setUploading] = useState(false);
    const [previewUrl, setPreviewUrl] = useState('');
    const fileInputRef = useRef<HTMLInputElement>(null);

    // 处理parentId: 转换"root"或"/"为null，其他情况转为数字
    const processedParentId = parentId === 'root' || parentId === null || parentId === "/" ? null : Number(parentId);

    // 上传文件处理函数
    const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (!file) return;

        // 验证文件类型，只允许图片
        if (!file.type.startsWith('image/')) {
            ToastUtil("请上传图片文件", '❌', "error");
            return;
        }

        // 显示本地预览
        const localPreviewUrl = URL.createObjectURL(file);
        setPreviewUrl(localPreviewUrl);

        // 准备上传
        setUploading(true);

        try {
            // 创建FormData
            const formData = new FormData();
            formData.append('file', file);

            // 业务ID可以是临时ID，等创建成功后再关联
            const tempBusinessId = 'temp-' + Date.now();

            // 调用文件上传接口
            const response = await axiosInstance.post(`/middleware/file/upload?businessId=${tempBusinessId}`,
                formData,
                {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }
            );

            const data = response.data;
            if (data.status && data.data) {
                // 确保只存储URL字符串
                const iconUrl = data.data.url || data.data;
                setFolderData({
                    ...folderData,
                    icon: iconUrl
                });
                ToastUtil("图标上传成功", '✅', "success");
            } else {
                ToastUtil(data.message || "上传失败", '❌', "error");
                // 清除预览
                URL.revokeObjectURL(localPreviewUrl);
                setPreviewUrl('');
            }
        } catch (error: any) {
            ToastUtil(error.message || "上传异常", '❌', "error");
            // 清除预览
            URL.revokeObjectURL(localPreviewUrl);
            setPreviewUrl('');
        } finally {
            setUploading(false);
        }
    };

    // 清除已上传的图标
    const clearUploadedIcon = () => {
        setFolderData({
            ...folderData,
            icon: ''
        });
        if (previewUrl) {
            URL.revokeObjectURL(previewUrl);
            setPreviewUrl('');
        }
        if (fileInputRef.current) {
            fileInputRef.current.value = '';
        }
    };

    const createFolder = async () => {
        try {
            const response = await axiosInstance.post("/app/collection", {
                "parentId": processedParentId,
                "name": folderData.name,
                "description": folderData.description,
                "icon": folderData.icon, // 确保这里只有URL字符串
                "emoji": emoji // 发送emoji字段
            });

            const data = response.data;
            if (data.status) {
                ToastUtil(data.message || "创建成功", '🥰', "success");
                /*发布消息更新文件夹列表*/
                PubSub.publish('refreshFolder', true);
                // 关闭弹窗
                onOpenChangeFolder();
                // 清除预览
                if (previewUrl) {
                    URL.revokeObjectURL(previewUrl);
                }
                // 重置表单
                setFolderData({
                    name: '',
                    description: '',
                    icon: '',
                });
                setPreviewUrl('');
            } else {
                ToastUtil(data.message || "创建失败", '😰', "error");
            }
        } catch (error: any) {
            ToastUtil(error.message || "操作异常", '🥸', "error");
        }
    }

    /*返回组件*/
    return (
        <>
            <Modal backdrop={"blur"} isOpen={isOpenFolder} onOpenChange={onOpenChangeFolder}
                placement={"auto"} size="md"
                isDismissable={false}>
                <ModalContent>
                    {
                        onClose => (
                            <>
                                <ModalHeader className={`dark:text-white light:text-black text-center`}>创建文件夹</ModalHeader>
                                <ModalBody>
                                    {/*Icon*/}
                                    <div className={'flex text-center justify-center items-center pb-3'}>
                                        <p className={`text-3xl shadow-sm border rounded-full p-2 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors`}
                                            onClick={(v) => {
                                                onOpenSelectEmoji()
                                            }}>{emoji}</p>
                                    </div>
                                    {/*表单*/}
                                    <Input
                                        type="text"
                                        label="名称"
                                        placeholder="请输入文件夹名称"
                                        variant="bordered"
                                        labelPlacement="outside"
                                        color={"primary"}
                                        value={folderData.name}
                                        onValueChange={(name) => {
                                            setFolderData({
                                                ...folderData,
                                                name
                                            })
                                        }}
                                        startContent={
                                            <BiFolderOpen
                                                className="text-2xl text-default-400 pointer-events-none flex-shrink-0" />
                                        }
                                        isRequired
                                    />

                                    {/* 文件上传区域 */}
                                    <div className="w-full space-y-2">
                                        <p className="text-sm text-default-500">图标上传</p>

                                        {previewUrl ? (
                                            <div className="relative w-full flex justify-center">
                                                <div className="relative w-24 h-24 border rounded-md overflow-hidden">
                                                    <Image
                                                        src={previewUrl}
                                                        alt="Icon preview"
                                                        className="w-full h-full object-center"
                                                    />
                                                    <Button
                                                        isIconOnly
                                                        size="sm"
                                                        color="danger"
                                                        variant="flat"
                                                        className="absolute top-1 right-1"
                                                        onClick={clearUploadedIcon}
                                                    >
                                                        <BiX />
                                                    </Button>
                                                </div>
                                            </div>
                                        ) : (
                                            <div
                                                className="w-full border-2 border-dashed border-default-200 rounded-lg p-4 flex flex-col items-center justify-center cursor-pointer hover:bg-default-100 transition-colors"
                                                onClick={() => fileInputRef.current?.click()}
                                            >
                                                <BiUpload className="text-2xl text-default-400" />
                                                <p className="text-sm text-default-500 mt-2">
                                                    {uploading ? "上传中..." : "点击上传图标（选填）"}
                                                </p>
                                                <input
                                                    type="file"
                                                    ref={fileInputRef}
                                                    className="hidden"
                                                    accept="image/*"
                                                    onChange={handleFileUpload}
                                                    disabled={uploading}
                                                />
                                            </div>
                                        )}
                                    </div>

                                    <Textarea
                                        className={"break-all dark:text-white light:text-black"}
                                        type="text"
                                        label="描述"
                                        placeholder="请输入文件夹描述（选填）"
                                        variant="bordered"
                                        labelPlacement="outside"
                                        color={"primary"}
                                        value={folderData.description}
                                        onValueChange={(description) => {
                                            setFolderData({
                                                ...folderData,
                                                description
                                            })
                                        }}
                                        startContent={
                                            <BiLabel
                                                className="text-2xl text-default-400 pointer-events-none flex-shrink-0" />
                                        }
                                    />
                                </ModalBody>
                                <ModalFooter className="justify-center">
                                    <Button className={"w-1/3"} color="primary"
                                        onClick={createFolder}
                                        isDisabled={!folderData.name.trim() || uploading}>
                                        {uploading ? "上传中..." : "创建"}
                                    </Button>
                                </ModalFooter>
                            </>
                        )
                    }
                </ModalContent>
            </Modal>
            {/*表情选择*/}
            <EmojiSelect isSelect={isSelectEmoji} onSelectChange={onSelectChange} setEmoji={setEmoji} />
        </>
    )
}